package com.xuetang9.fujian.threaddemo.downloader;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author: fujian
 * @description:
 * @date: 2021/5/2 14:53
 * @version: V1.0
 * @package: com.xuetang9.fujian.threaddemo.downloader
 **/
public class DownloadApp {
    private static final String path = "http://www.xuetang9.com/templets/default/video/intro.mp4";
    private static final int ThreadCount = 5;  // 线程总数
    private static final String partFilePath = "intro.mp4";
    public static void main(String[] args) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
        connection.setRequestProperty("Range", "bytes=0-");
        connection.connect();
        if (connection.getResponseCode() / 100 != 2){
            return;
        }
        int contentLength = connection.getContentLength();
        int partSize = contentLength / ThreadCount;
        for (int i = 0; i < ThreadCount; i++) {
            int startPosition = i * partSize;
            RandomAccessFile partFile = new RandomAccessFile(partFilePath,"rw");
            partFile.seek(startPosition);
            // 最后一个文件块的大小，需要重新计算
            if (i == ThreadCount -1){
                partSize += contentLength % ThreadCount;
            }
            new Thread(new DownloadTask(path,startPosition, partSize ,partFile)).start();
        }
        System.out.println("-------------------------");
    }
}
